package com.yun.zhong.fu.usercenter.rocketmq;

import com.yun.zhong.fu.usercenter.dao.BonusEventLogDao;
import com.yun.zhong.fu.usercenter.dao.UserDao;
import com.yun.zhong.fu.usercenter.dto.message.UserAddBonusMsgDTO;
import com.yun.zhong.fu.usercenter.entity.BonusEventLog;
import com.yun.zhong.fu.usercenter.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author RenPu
 * @Date 2021/1/4 12:29
 * @Version 1.0
 * @Description:
 **/

@Service
//配置消费者的组名称，以及topic名称，必须要与消息生产者保持一致
@RocketMQMessageListener(consumerGroup = "test-group", topic = "add-bonus")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class AddBounsMessageListener implements RocketMQListener<UserAddBonusMsgDTO> {
    private final UserDao userDao;

    private final BonusEventLogDao bonusEventLogDao;


    @Override
    public void onMessage(UserAddBonusMsgDTO userAddBonusMsgDTO) {
        Integer bonus = userAddBonusMsgDTO.getBounus();

        //当收到消息的时候，执行业务
        Integer userId = userAddBonusMsgDTO.getUserId();
        User user = this.userDao.getById(userId);
        //1：根据用户的id，进行对用户的积分进行 累加
        Integer addBouns = user.getBonus() + bonus;
        user.setBonus(addBouns);
        this.userDao.updateByPrimaryKeySelective(user);
        //2:把此次的积分累加的操作，记录到event_log
        this.bonusEventLogDao.insert(
                BonusEventLog
                        .builder()
                        .event("CONTRIBUTE")
                        .description("投稿加积分....")
                        .userId(userId)
                        .value(bonus)
                        .createTime(new Date())
                        .build());


        log.info("积分添加完毕.....");
    }
}
